package com;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class WbServlet extends HttpServlet {
    DbUtil dbUtil = new DbUtil();
    private String message;

    public void init() throws ServletException
    {
        // 执行必需的初始化
        message = "Hello World######";
    }

    public void doPost(HttpServletRequest request,
                       HttpServletResponse response)
            throws ServletException, IOException
    {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        try {
            Users dbUser = dbUtil.getUser(username, password);
            if(dbUser != null){
                //TODO 数据库查询
                if(null != username && username.equals(dbUser.getUsername()) && null != password && password.equals(dbUser.getPassword())){

                    response.sendRedirect("main_ajax.jsp");
                }else{
                    request.setAttribute("errorInfo","账号或密码不正确。");
                    request.getRequestDispatcher("/index.jsp").forward(request,response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("/index.jsp");
        }

        // 设置响应内容类型，告诉流浪器返回的数据类型
//        response.setContentType("application/json");
//        response.setCharacterEncoding("utf-8");
//        //TODO 看数据库如何查询获得数据
//         String userInfo = "{\"username\":\"张三\",\"pas\":\"123\"}";
//        // 实际的逻辑是在这里
//        PrintWriter out = response.getWriter();
//        out.println(userInfo);
//        out.close();
    }

    public void destroy()
    {
        // 什么也不做
    }
}
